package cn.zcy.dao.impl;

import cn.zcy.dao.AccountDao;
import cn.zcy.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(Account account) {
        jdbcTemplate.update("insert into account (id,username,money) values (?,?,?)", account.getId(), account.getUsername(), account.getMoney());
    }

    @Override
    public void update(Account account) {
    jdbcTemplate.update("update account set username=?, money=? where id=?",account.getUsername(),account.getMoney(),account.getId());
    }

    @Override
    public void delete(Integer id) {

    }

    @Override
    public void transfer(String sourceName, String targeName, Double money) {

    }

    @Override
    public Account findAccountById(Integer id) {
        Account account = jdbcTemplate.queryForObject("select * from account where id=? ", new Object[]{id}, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                Account account = new Account();
                account.setId(rs.getInt("id"));
                account.setUsername(rs.getString("username"));
                account.setMoney(rs.getDouble("money"));
                // 设置其他字段
                return account;
            }
        });
        return account;

//        List<Account> accountList = jdbcTemplate.query("select * from account where id=? ", new BeanPropertyRowMapper<Account>(Account.class), id);
//        return accountList.isEmpty() ? null : accountList.get(0);
    }

    @Override
    public List<Account> findAll() {
//        List<Account> query = jdbcTemplate.query("select * from account", (rs, rowNum) -> {
//            Account account = new Account();
//            account.setId(rs.getInt("id"));
//            account.setUsername(rs.getString("username"));
//            account.setMoney(rs.getDouble("money"));
//            // 设置其他字段
//            return account;
//        });
//        return query;

        return jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
    }

    @Override
    public Account findByName(String username) {
        List<Account> accountList = jdbcTemplate.query("select * from account where username=?", new BeanPropertyRowMapper<Account>(Account.class), username);
        return accountList.isEmpty() ? null : accountList.get(0);
    }
}
